# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  #in case someone tries to give in a url that would otherwise cause a routing error.
  rescue_from ActionController::RoutingError do |exception|
    flash[:notice] = "Sorry, we didn't recognize your URL.  Taking you back to the shop."
    redirect_to(:controller => 'store', :action => 'index')
  end
  
  layout 'store'
  before_filter :authorize, :except => :login # if you don't want to authorize, override the authorize method in sub-controllers and have it do nothing.
  helper :all # include all helpers, all the time
  protect_from_forgery # See ActionController::RequestForgeryProtection for details
  
  protected 
  # THIS IS WHITELISTING.  This method gets called on every controller unless you override it with nothing.  Look at the store controller for example.
  def authorize
    @user = User.find_by_id(session[:user_id]) 
    logger.debug @user
    unless (@user && @user.isAdmin?)
      session[:original_uri] = request.request_uri # keep the address of where they were
      flash[:notice] = "Please log in [Administrators only]" 
      redirect_to :controller => 'admin', :action => 'login'
    end 
  end
  
  #THIS METHOD IS ACCESSIBLE TO ALL CONTROLLERS
  def find_user
    @user = User.find_by_id(session[:user_id]) # will return nil if not found
  end
  
end
